package com.itheima.service.impl;

import com.itheima.exception.DeptNotAllowedDeleteException;
import com.itheima.mapper.DeptMapper;
import com.itheima.pojo.domain.Dept;
import com.itheima.pojo.domain.Emp;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Override
    public List<Dept> list() {
        List<Dept> list = deptMapper.list();
        return list;
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        // 1.查询该部门下是否有员工
        List<Emp> emps = deptMapper.listByDeptId(id);
        // 2.有员工则不允许删除
        if (emps.size() > 0) {
            throw new DeptNotAllowedDeleteException("该部门下有员工，不允许删除");
        }

        deptMapper.deleteDeptById(id);

        deptMapper.deleteEmpById(id);

    }

    @Override
    public void add(Dept dept) {
        //1. 补全基础属性
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        //2. 调用Mapper接口
        deptMapper.insert(dept);
    }


    @Override
    public void update(Dept dept) {
        //1. 补全属性
        dept.setUpdateTime(LocalDateTime.now());
        //2. 调用Mapper
        deptMapper.update(dept);
    }

    @Override
    public Dept findById(Integer id) {
        Dept deptList = deptMapper.findById(id);
        return deptList;
    }
}
